import './index.scss'
const src = chrome.runtime.getURL('src/content-script/iframe/index.html')
let contentWindow: any = null
let currentTabInfo: any = null
let innerHTML: string = ''
let targetObject: HTMLElement

const startIframe = () => {
  const iframe = new DOMParser().parseFromString(
    `<iframe class="crx-iframe" src="${src}" id="iframeaaa"></iframe>`,
    'text/html'
  ).body.firstElementChild
  
  if (iframe) {
    document.body?.append(iframe)
    if (iframe && iframe instanceof HTMLElement) {
      iframe.onload = function () {
        contentWindow = (iframe as HTMLIFrameElement).contentWindow
        console.log('start contentWindow:', contentWindow)
        contentWindow.postMessage('11111')
        // chrome.runtime.openOptionsPage()
        // window.addEventListener(
        //   'message',
        //   (e) => {
        //     alert('from parent')
        //     console.log(e.origin) //子页面URL，这里是http://b.index.com
        //     console.log(e.source) // 子页面window对象，全等于iframe.contentWindow
        //     console.log(e.data) //子页面发送的消息
        //   },
        //   false
        // )
      }
    }
  }
}

self.onerror = function (message, source, lineno, colno, error) {
  console.info(
    `Error: ${message}\nSource: ${source}\nLine: ${lineno}\nColumn: ${colno}\nError object: ${error}`
  )
}

/**
 * 创建一个dom遮罩层
 */
function createMask() {
  const mask = document.createElement('div')
  // 必须让鼠标指针能够穿透 mask 元素
  mask.style.pointerEvents = 'none'
  mask.style.background = 'rgb(3, 132, 253, 0.22)'
  mask.style.position = 'fixed'
  mask.style.zIndex = '9999999999999'
  mask.style.display = 'none'
  // mask.style.border = "5px solid black";
  document.body.appendChild(mask)
  return mask
}
// 聚焦 dom 的遮罩
var maskDom = createMask()
// 是否为选择模式，可以使用鼠标指针选择字段进行编辑,由平台程序改变
var isSelectModel = false
// 鼠标是否按下状态
var isMousedown = false
var target: any = null
// 为防止页面上面有禁止冒泡的元素。所以使用 mouse 实现点击监听
// window.globalClickMouseDowned = null;
// window.globalClickDownTime = null;

function listenerMousedown(event: any) {
  if (!isSelectModel) return
  target.style.pointerEvents = 'none'

  isMousedown = true
  if (event.which === 1) {
    // window.globalClickMouseDowned = true;
    // window.globalClickDownTime = new Date().getTime();
  }
}

async function listenerMouseup(event: any) {
  console.log('listenerMouseup', event)
  event.preventDefault()
  if (!isSelectModel) return
  isMousedown = false
  target.style.pointerEvents = 'auto'

  // 关闭 选择模式
  isSelectModel = false
  maskDom.style.display = 'none'

  if (innerHTML) {
    // console.dir(target)
    const frameDOM = document.querySelector('#iframeaaa')

    if (frameDOM && frameDOM instanceof HTMLElement) {
      contentWindow = (frameDOM as HTMLIFrameElement).contentWindow
      // console.log('contentWindow:', frameDOM, contentWindow)
      console.dir(frameDOM)
      const url = chrome.runtime.getURL('src/options/index.html#/options')
      console.log(url);
      // storage.clearNewEvent()
      const sendData = {
        ...currentTabInfo,
        innerHTML,
        class: targetObject.classList[0],
        outerHTML: targetObject.outerHTML,
        monitorId: new Date().getTime(),
        monitorName: '自定义监控',
        monitorInterval: 60, // todo: options
        monitor: false
      }
      chrome.storage.local.set({'tempData': sendData})
      // chrome.runtime.sendMessage({event: "addMonitor", data: sendData })
      // frameDOM && storage.saveNewEvent(sendData)
      window.open(url, '_blank')
      contentWindow.postMessage('11111')
      contentWindow.postMessage({
        a: 1,
        b: 2,
      })
    }
  }
  // 点击某个 dom
  // if (window.globalClickMouseDowned && event.which === 1) {
  //     window.globalClickMouseDowned = false;
  //     const now = new Date().getTime();
  //     if (now - window.globalClickDownTime < 300) {

  //         // 关闭 选择模式
  //         isSelectModel = false;
  //         maskDom.style.display = "none";

  //         const infos = {
  //             x: parseInt(maskDom.style.left),
  //             y: parseInt(maskDom.style.top),
  //             w: parseInt(maskDom.style.width),
  //             h: parseInt(maskDom.style.height)
  //         };
  //         // console.log('dom infos: ', infos);
  //         // 返回整个屏幕截图
  //         // const screen_image = await chrome.runtime.sendMessage({ type: "screenshot" });
  //         // if (!screen_image.image) {
  //         //     alert(chrome.i18n.getMessage('errorMsg'))
  //         //     return;
  //         // }
  //         // const crop_image = await crop(screen_image.image, infos);
  //         // copy_img_to_clipboard(crop_image);

  //     }
  // }
}

function listenerMousemove(event: any) {
  if (!isSelectModel) return
  /**
   * 鼠标移入时的高亮处理
   */
  if (!isMousedown) {
    // 拿到鼠标移入的元素集合
    const paths = document.elementsFromPoint(event.x, event.y)
    // 这里取第一个就行
    target = paths[0]
    // console.log("target:", target);
    if (target) {
      // console.dir(target)
      console.dir(target)
      console.log(target.innerHTML, target.outerHTML)
      innerHTML = target.innerHTML
      targetObject = target
      // post
      // selectInnerHTML = target.innerHTML
      // 拿到元素的坐标信息
      const targetDomInfo = target.getBoundingClientRect()
      const h = targetDomInfo.height,
        w = targetDomInfo.width,
        l = targetDomInfo.left,
        t = targetDomInfo.top
      maskDom.style.width = w + 'px'
      maskDom.style.height = h + 'px'
      maskDom.style.left = l + 'px'
      maskDom.style.top = t + 'px'
      maskDom.style.display = 'block'
    } else {
      maskDom.style.display = 'none'
    }
  }
}

function isIFrame(element: Element): element is HTMLIFrameElement {
  return element instanceof HTMLIFrameElement
}

/** 各类鼠标事件监听 **/
document.addEventListener('mousedown', listenerMousedown)
document.addEventListener('mouseup', listenerMouseup)
document.addEventListener('mousemove', listenerMousemove)
chrome.runtime.onMessage.addListener((req, sender, res) => {
  // alert(JSON.stringify(req))
  // alert(JSON.stringify(sender))
  // alert(JSON.stringify(res))
  startIframe()
  currentTabInfo = req.currentTabInfo
  if (req.type === 'select-dom') {
    // 启动选择dom截图
    isSelectModel = true
  }
  // if (req.type === 'area-screenshot') {
  //     // 启动选择区域截图
  //     area_screenshot();
  // }
  return true
})
